import { getToken } from '../utils/auth/tokenStorage';
import { API_BASE_URL } from '../constants/api';
import axios from 'axios';
import { Alert } from 'react-native/Libraries/Alert/Alert';

// 导出API_BASE_URL以便其他地方使用
export { API_BASE_URL };

interface ApiOptions {
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  headers?: Record<string, string>;
  body?: any;
  requireAuth?: boolean;
}

/**
 * 通用API服务适配器
 * 处理所有API请求，自动添加认证信息，处理错误等
 */
export async function apiRequest<T = any>(
  endpoint: string, 
  options: ApiOptions = { method: 'GET', requireAuth: true }
): Promise<T> {
  const { method = 'GET', headers = {}, body, requireAuth = true } = options;
  
  // 构建请求URL
  const url = `${API_BASE_URL}${endpoint}`;
  console.log("请求URL:", url);
  // 请求头
  const requestHeaders: Record<string, string> = {
    'Content-Type': 'application/json',
    ...headers
  };
  
  // 如果需要身份验证，添加token
  if (requireAuth) {
    const token = await getToken();
    if (token) {
      requestHeaders['Authorization'] = `Bearer ${token}`;
      // 添加JWT调试日志
      try {
        const tokenParts = token.split('.');
        if (tokenParts.length === 3) {
          const payload = JSON.parse(atob(tokenParts[1]));
          console.log('发送请求使用的JWT令牌信息:', {
            id: payload.id,
            userId: payload.userId,
            exp: payload.exp ? new Date(payload.exp * 1000).toISOString() : 'none'
          });
        }
      } catch (e) {
        console.error('解析令牌失败:', e);
      }
    } else {
      throw new Error('未授权，请先登录');
    }
  }
  
  // 构建请求配置
  const config: RequestInit = {
    method,
    headers: requestHeaders,
  };
  
  // 如果有请求体，添加到配置中
  if (body) {
    config.body = JSON.stringify(body);
  }
  
  try {
    const response = await fetch(url, config);
    
    // 处理非2xx响应
    if (!response.ok) {
      if (response.status === 401) {
        throw new Error('未授权，请先登录');
      }
      const errorData = await response.json().catch(() => ({ error: '服务器错误' }));
      throw new Error(errorData.error || `请求失败: ${response.status}`);
    }
    
    // 解析响应
    const data = await response.json();
    return data;
  } catch (error: any) {
    console.error('API请求错误:', error);
    throw error;
  }
}

/**
 * API服务，包含所有接口方法
 */
export const apiService = {
  // 用户身份验证
  auth: {
    login: (userId: string, password: string) => 
      apiRequest('/api/auth/login', { 
        method: 'POST', 
        body: { userId, password },
        requireAuth: false 
      }),
    logout: () => apiRequest('/api/auth/logout', { method: 'POST' }),
  },
  
  // 收据/发票相关接口
  receipts: {
    list: (params?: {
      searchQuery?: string;
      themeFilter?: string;
      statusFilter?: string;
      dateFilter?: string;
    }) => {
      const queryParams = new URLSearchParams();
      if (params) {
        if (params.searchQuery) queryParams.set('searchQuery', params.searchQuery);
        if (params.themeFilter) queryParams.set('themeFilter', params.themeFilter);
        if (params.statusFilter) queryParams.set('statusFilter', params.statusFilter);
        if (params.dateFilter) queryParams.set('dateFilter', params.dateFilter);
      }
      
      const queryString = queryParams.toString();
      return apiRequest(`/api/receipts/list${queryString ? `?${queryString}` : ''}`);
    },
    
    get: (serialNo: string) => apiRequest(`/api/receipts/get?receiptSerialNo=${serialNo}`),
    
    upload: (formData: FormData) => {
      // 使用axios替代XMLHttpRequest以更好地处理FormData
      return new Promise(async (resolve, reject) => {
        try {
          const token = await getToken();
          if (!token) {
            throw new Error('未授权，请先登录');
          }
          
          const url = `${API_BASE_URL}/api/receipts/attachment/upload`;
          console.log("上传收据URL:", url);
          
          // 使用axios进行上传
          const response = await axios.post(url, formData, {
            headers: {
              'Authorization': `Bearer ${token}`,
              'Accept': 'application/json',
              'Content-Type': 'multipart/form-data'
            },
            // 添加上传进度监听
            onUploadProgress: (progressEvent) => {
              const percentCompleted = Math.round((progressEvent.loaded * 100) / (progressEvent.total || 1));
              console.log('上传进度:', percentCompleted + '%');
            }
          });
          
          resolve(response.data);
        } catch (error: any) {
          console.error('上传收据失败:', error);
          
          if (error.response) {
            // 服务器返回了错误响应
            console.error('服务器响应错误:', error.response.data);
            reject(new Error(`服务器返回错误: ${error.response.status} - ${error.response.data?.message || '服务器错误'}`));
          } else if (error.request) {
            // 请求已经发出，但没有收到响应
            reject(new Error('无法连接到服务器'));
          } else {
            // 请求配置时出现错误
            reject(error);
          }
        }
      });
    }
  },
  
  // 主题管理相关接口
  themes: {
    list: () => apiRequest('/api/themes/search', { 
      method: 'POST', 
      body: {} 
    }),
    get: (serialNo: string) => apiRequest(`/api/themes/get?id=${serialNo}`),
    create: (data: any) => apiRequest('/api/themes/save', { 
      method: 'POST', 
      body: data 
    }),
    update: (data: any) => apiRequest('/api/themes/save', { 
      method: 'POST', 
      body: data 
    }),
  },
  
  // 用户相关接口
  users: {
    search: (query: string = '') => apiRequest(`/api/users/search?query=${encodeURIComponent(query)}`, {
      method: 'POST',
      body: []
    })
  }
};

// 导出默认的API服务
export default apiService; 